package com.itheima.stock.helper;

import com.google.common.util.concurrent.RateLimiter;
import com.itheima.stock.enums.CodeEnum;
import com.itheima.stock.response.ResponseResult;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class LimterAspect {

    @Autowired
    private RateLimiter rateLimiter;

    @Pointcut(value = "@annotation(com.itheima.stock.annotation.Limter)")
    public void pt(){}

    @Around("pt()")
    public Object limter(ProceedingJoinPoint pjp) throws Throwable {

        boolean b = rateLimiter.tryAcquire();

        if(b){
            return pjp.proceed();
        }else {
            return ResponseResult.error(CodeEnum.OVER_CONCURRENCY_NUM);
        }

    }
}
